package com.heima.exam.p5;

import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.UUID;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

public class Server {
    public static void main(String[] args) throws IOException {
        ServerSocket ss = new ServerSocket(20000);
        Socket accept = ss.accept();
        Upload p = new Upload(accept);
        ThreadPoolExecutor pool = new ThreadPoolExecutor(5, 8, 2, TimeUnit.SECONDS, new ArrayBlockingQueue<>(6));
        pool.execute(p);
    }


}

class Upload implements Runnable {
    Socket accept;

    public Upload(Socket accept) {
        this.accept = accept;
    }

    @Override
    public void run() {
        try {
            InputStream inputStream = accept.getInputStream();
            String replace = UUID.randomUUID().toString().replace("-", "");
            FileOutputStream fos = new FileOutputStream("src/com/heima/exam/p5/" + replace + ".jpg");
            byte[] bytes = new byte[1024];
            int len;
            while ((len = inputStream.read(bytes)) != -1) {
                fos.write(bytes, 0, len);
            }
            OutputStream outputStream = accept.getOutputStream();
            outputStream.write("hehe".getBytes());

            outputStream.close();
            inputStream.close();
            fos.close();
            accept.close();

        } catch (Exception e) {
            throw new RuntimeException(e);
        }

    }
}